package com.dwxt.mall.controller;

import com.alipay.api.AlipayApiException;
import com.dwxt.common.annotation.ValidateFiled;
import com.dwxt.common.annotation.ValidateGroup;
import com.dwxt.common.base.BaseResult;
import com.dwxt.mall.entity.PayOrder;
import com.dwxt.mall.service.ZFBService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@RequestMapping("/mall/zfb")
@RestController
@Slf4j
public class ZFBPayController {
    @Autowired
    private ZFBService zfbService;

    /**
     * showdoc
     *
     * @param number    必选 int 购买数量
     * @param integral  必选 int 消耗积分
     * @param realPrice 必选 double 实际费用
     * @param productId 商城必选 int 产品id
     * @param addressId 商城必选 int 地址id
     * @param category  赛事必选 string 订单种类(race)
     * @param name      赛事必选 string 赛事名称
     * @return {"status":200,"msg":"SUCCESS","data":{}}
     * @catalog 商城/订单
     * @title 支付宝支付
     * @description 获取支付宝支付的必要参数并创建待支付订单
     * @url /mall/zfb/createOrderWithZFB
     */
    @RequestMapping("/createOrderWithZFB")
    @ValidateGroup(fileds = {
            @ValidateFiled(index = 0, filedName = "number", notNull = true),
            @ValidateFiled(index = 0, filedName = "integral", notNull = true),
            @ValidateFiled(index = 0, filedName = "realPrice", notNull = true),

    })
    public BaseResult createOrderWithZFB(PayOrder order) throws AlipayApiException {
        synchronized (ZFBPayController.class){
            return zfbService.createOrderWithZFB(order);
        }
    }

    /**
     * 支付宝支付回调
     *
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("/notifyUrl")
    public void notifyUrl(HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter responseWriter = response.getWriter();
        try {
            Map<String, String> params = getZFBRespMap(request);
            String result = zfbService.checkParamsZFB(params);
            responseWriter.write(result);
        } catch (Exception e) {
            log.error(e.toString());
            responseWriter.write("fail");
        }
    }

    private Map<String, String> getZFBRespMap(HttpServletRequest request) {
        Map<String, String> params = new HashMap<String, String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            log.info(name + "：" + valueStr);
            params.put(name, valueStr);
        }
        return params;
    }

}
